package com.zl.bootsecurityjwt.common.aspect;

import com.alibaba.fastjson.JSON;

import com.zl.bootsecurityjwt.common.annotation.ExtAuthorize;
import com.zl.bootsecurityjwt.common.exception.PreAuthorizeException;
import com.zl.bootsecurityjwt.common.jwt.JwtTokenTemplate;
import com.zl.bootsecurityjwt.model.LoginUser;
import com.zl.bootsecurityjwt.service.JwtUserDetailsService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.PatternMatchUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.util.Collection;

/**
 * 自定义权限实现
 *
 * @author cqrec
 */
@Aspect
@Component
public class ExtAuthorizeAspect
{
    @Autowired
    private JwtUserDetailsService tokenService;

    /** 所有权限标识 */
    private static final String ALL_PERMISSION = "*:*:*";

    /** 管理员角色权限标识 */
    private static final String SUPER_ADMIN = "admin";

    /** 数组为0时 */
    private static final Integer ARRAY_EMPTY = 0;

    @Around("@annotation(com.zl.bootsecurityjwt.common.annotation.ExtAuthorize)")
    public Object around(ProceedingJoinPoint point) throws Throwable
    {
        Signature signature = point.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        ExtAuthorize annotation = method.getAnnotation(ExtAuthorize.class);
        if (annotation == null)
        {
            return point.proceed();
        }


        String hasExtPermi = annotation.hasExtPermi();
        if (!StringUtils.isEmpty(hasExtPermi))
        {
            // 如果存在{}变量时，处理方法，必须配合 @PostMapping || @GetMapping || @RequestMapping，注解的参数
            // 例1：@PreAuthorize(hasPermi = "module:controller:{code}")
            //    @GetMapping("/{code}")
            // 例2：@PreAuthorize(hasPermi = "module:controller:{type}:{code}")
            //    @GetMapping("/{type}/{code}")
            /*if (hasExtPermi.contains("{")) {
                String[] parameterNames = methodSignature.getParameterNames();
                Object[] paramValues = point.getArgs();

                for (int i = 0; i < parameterNames.length; i++) {
                    hasExtPermi = hasExtPermi.replace("{" + parameterNames[i] + "}", String.valueOf(paramValues[i]));
                }
            }*/

            if (hasExtPermi(hasExtPermi))
            {
                return point.proceed();
            }
            throw new PreAuthorizeException();
        }
        else if (!StringUtils.isEmpty(annotation.lacksExtPermi()))
        {
            if (lacksExtPermi(annotation.lacksExtPermi()))
            {
                return point.proceed();
            }
            throw new PreAuthorizeException();
        }
        else if (ARRAY_EMPTY < annotation.hasAnyExtPermi().length)
        {
            if (hasAnyExtPermi(annotation.hasAnyExtPermi()))
            {
                return point.proceed();
            }
            throw new PreAuthorizeException();
        }
        else if (!StringUtils.isEmpty(annotation.hasExtRole()))
        {
            if (hasExtRole(annotation.hasExtRole()))
            {
                return point.proceed();
            }
            throw new PreAuthorizeException();
        }
        else if (!StringUtils.isEmpty(annotation.lacksExtRole()))
        {
            if (lacksExtRole(annotation.lacksExtRole()))
            {
                return point.proceed();
            }
            throw new PreAuthorizeException();
        }
        else if (ARRAY_EMPTY < annotation.hasAnyExtRoles().length)
        {
            if (hasAnyExtRoles(annotation.hasAnyExtRoles()))
            {
                return point.proceed();
            }
            throw new PreAuthorizeException();
        }

        return point.proceed();
    }

    /**
     * 验证用户是否具备某权限
     *
     * @param permission 权限字符串
     * @return 用户是否具备某权限
     */
    public boolean hasExtPermi(String permission)
    {
        LoginUser userInfo = tokenService.getUserList();;
        if (StringUtils.isEmpty(userInfo) || CollectionUtils.isEmpty(userInfo.getPermissions()))
        {
            return false;
        }
        return hasPermissions(userInfo.getPermissions(), permission);
    }

    /**
     * 验证用户是否不具备某权限，与 hasPermi逻辑相反
     *
     * @param permission 权限字符串
     * @return 用户是否不具备某权限
     */
    public boolean lacksExtPermi(String permission)
    {
        return hasExtPermi(permission) != true;
    }

    /**
     * 验证用户是否具有以下任意一个权限
     *
     * @param permissions 权限列表
     * @return 用户是否具有以下任意一个权限
     */
    public boolean hasAnyExtPermi(String[] permissions)
    {
        LoginUser userInfo = null;
        if (StringUtils.isEmpty(userInfo) || CollectionUtils.isEmpty(userInfo.getPermissions()))
        {
            return false;
        }
        Collection<String> authorities = userInfo.getPermissions();
        for (String permission : permissions)
        {
            if (permission != null && hasPermissions(authorities, permission))
            {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断用户是否拥有某个角色
     *
     * @param role 角色字符串
     * @return 用户是否具备某角色
     */
    public boolean hasExtRole(String role)
    {
        LoginUser userInfo = null;
        if (StringUtils.isEmpty(userInfo) || CollectionUtils.isEmpty(userInfo.getRoles()))
        {
            return false;
        }
        for (String roleKey : userInfo.getRoles())
        {
            if (SUPER_ADMIN.equals(roleKey) || roleKey.equals(role))
            {
                return true;
            }
        }
        return false;
    }

    /**
     * 验证用户是否不具备某角色，与 isRole逻辑相反。
     *
     * @param role 角色名称
     * @return 用户是否不具备某角色
     */
    public boolean lacksExtRole(String role)
    {
        return hasExtRole(role) != true;
    }

    /**
     * 验证用户是否具有以下任意一个角色
     *
     * @param roles 角色列表
     * @return 用户是否具有以下任意一个角色
     */
    public boolean hasAnyExtRoles(String[] roles)
    {
        LoginUser userInfo = null;
        if (StringUtils.isEmpty(userInfo) || CollectionUtils.isEmpty(userInfo.getRoles()))
        {
            return false;
        }
        for (String role : roles)
        {
            if (hasExtRole(role))
            {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断是否包含权限
     *
     * @param authorities 权限列表
     * @param permission 权限字符串
     * @return 用户是否具备某权限
     */
    private boolean hasPermissions(Collection<String> authorities, String permission)
    {
        return authorities.stream().filter(StringUtils::hasText)
                .anyMatch(x -> ALL_PERMISSION.contains(x) || PatternMatchUtils.simpleMatch(permission, x));
    }
    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray) {
        String params = "";
        if (paramsArray != null && paramsArray.length > 0) {
            for (int i = 0; i < paramsArray.length; i++) {
                
                    try {
                        Object jsonObj = JSON.toJSON(paramsArray[i]);
                        params += jsonObj.toString() + " ";
                    } catch (Exception e) {

                }
            }
        }
        return params.trim();
    }
}
